package com.kinghood.authoritycenter.common.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.kinghood.authoritycenter.common.model.constant.AuthConstant;
import com.kinghood.authoritycenter.common.model.dao.auth.OpenAccountDO;
import com.kinghood.authoritycenter.common.model.dto.auth.KingHoodPrincipal;
import com.kinghood.authoritycenter.common.model.dto.auth.UserDTO;

import java.util.Date;
import java.util.Objects;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2023-12-07 17:18
 **/
public class KingHoodPrincipalBuilder {

    /**
     * token解析封装上下文
     * */
    public static KingHoodPrincipal getInstance(String issuer, String audience, String subject, Date expiration, String info) {
        if (Objects.equals(issuer, AuthConstant.ISSUER_INNER)) {
            UserDTO userDetail = JSON.parseObject(info, UserDTO.class);
            KingHoodPrincipal<UserDTO> res = new KingHoodPrincipal<>();
            res.setIssuer(issuer);
            res.setAudience(audience);
            res.setSubject(subject);
            res.setInfo(userDetail);
            res.setExpiration(expiration);
            res.setExpire(DateUtil.between(new Date(), expiration, DateUnit.SECOND, true));
            return res;
        }

        if (Objects.equals(issuer, AuthConstant.ISSUER_OPEN)) {
            OpenAccountDO openAccountDO = JSON.parseObject(info, OpenAccountDO.class);
            KingHoodPrincipal<OpenAccountDO> res = new KingHoodPrincipal<>();
            res.setIssuer(issuer);
            res.setAudience(audience);
            res.setSubject(subject);
            res.setInfo(openAccountDO);
            res.setExpiration(expiration);
            res.setExpire(DateUtil.between(new Date(), expiration, DateUnit.SECOND, true));
            return res;
        }
        return null;
    }

    public static <T> KingHoodPrincipal<T> getInstance(String issuer, String audience, String subject, T info) {
        KingHoodPrincipal res = new KingHoodPrincipal<>();
        res.setIssuer(issuer);
        res.setAudience(audience);
        res.setSubject(subject);
        res.setInfo(info);
        return res;
    }
}
